#Copyright (c) 2021 zhanghw
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

#!/bin/bash

#if [ $# -lt 1 ];then
#	echo "Usasges:"
#	echo "subgitinfo.sh workpath"
#	exit
#fi


function helpinfo(){
	echo "Usages:"
	echo "./gbox-list.sh            :show subgit info"
	echo "./gbox-list.sh help       :show help"
	echo "./gbox-list.sh save       :save subgit info to gbox/subgit.list"
	echo 
}

WorkDir=.
WorkPath=`pwd`
GboxPath="$WorkPath""/gbox"
SubgitListFname="subgit.list"
SubgitListPath="$GboxPath""/""$SubgitListFname"
SubgitListFnameTouched=0
SubgitNames=`find $WorkDir -name "*.git"`

PARM01=$1

if [ "$PARM01" = "help" ];then
	helpinfo
	exit
fi

for n in $SubgitNames
do
	subGitDir=${n%/*}
	#echo $subGitDir
	#continue
	if [ -d "$subGitDir/.git" ];then
		if [ "$subGitDir" = "$WorkDir" ];then
			continue
		fi
		cd $subGitDir >/dev/null
		Gitlog=`git log --pretty=format:"%H,%ad/"`
		GitRemote=`git remote`
		GitURL=`git remote get-url --push $GitRemote`
		GitBranch=`git branch | awk  '$1 == "*"{print $2}'`

		Gitlog=${Gitlog%%/*}

		if [ "$PARM01" = "save" ];then
			if [ ! -d  "$GboxPath" ];then
				mkdir $GboxPath
			fi
			if [ $SubgitListFnameTouched -eq 0 ];then
				if [ -f "$SubgitListPath" ];then
					rm -f $SubgitListPath
				fi
				SubgitListFnameTouched=1
			fi
			echo "|  I0=$subGitDir  |  I1=$GitRemote  |  I2=$GitURL  |  I3=$GitBranch  |  I4=$Gitlog  |" >> $SubgitListPath
			echo "Saved $subGitDir git info >>>>>>>> $SubgitListPath"
		else
			echo "|  I0=$subGitDir  |  I1=$GitRemote  |  I2=$GitURL  |  I3=$GitBranch  |  I4=$Gitlog  |"
		fi
		cd - >/dev/null
	fi
done


